﻿#include "Readline.h"

namespace Lisp
{

  bool Readline::Get(const std::string &prompt, std::string &input)
  {
    std::cout << prompt;
    input.clear();

    int circleBracket = 0;
    int squareQuote = 0;
    int curlyQuote = 0;

    do
    {
      std::string line;
      std::getline(std::cin, line);
      bool error = false;
      for (auto c : line)
      {
        if (c == '(')
        {
          circleBracket++;
        }
        else if (c == ')')
        {
          if (circleBracket > 0)
          {
            circleBracket--;
          }
          else
          {
            std::cout << "Error: unmatch ')'" << std::endl;
            error = true;
            break;
          }
        }

        else if (c == '[')
        {
          squareQuote++;
        }
        else if (c == ']')
        {
          if (squareQuote > 0)
          {
            squareQuote--;
          }
          else
          {
            std::cout << "Error: unmatch ']'" << std::endl;
            error = true;
            break;
          }
        }
        else if (c == '{')
        {
          curlyQuote++;
        }
        else if (c == '}')
        {
          if (curlyQuote > 0)
          {
            curlyQuote--;
          }
          else
          {
            std::cout << "Error: unmatch '}'" << std::endl;
            error = true;
            break;
          }
        }
      }

      if (error)
      {
        error = false;
        std::cout << prompt;
        line.clear();
        continue;
      }

      input += line + "\n";

      if (circleBracket == 0 && squareQuote == 0 && curlyQuote == 0)
      {
        break;
      }

    } while (1);

    return true;
  }

}